package dao;

import pojo.Order;
import utils.JDBCUtils;

import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class OrderDAO {

    private static final String TABLE_NAME = "tb_orders";

    // 添加订单
    public static void addOrder(Order order) throws SQLException {
        String sql = "INSERT INTO " + TABLE_NAME + " (user_id, order_date, total_amount, payment_status, shipping_address) VALUES (?, ?, ?, ?, ?)";
        JDBCUtils.execute(sql, order.getUserId(), order.getOrderDate(), order.getTotalAmount(), order.getPaymentStatus(), order.getShippingAddress());
    }

    // 更新订单信息
    public static void updateOrder(Order order) throws SQLException {
        String sql = "UPDATE " + TABLE_NAME + " SET user_id = ?, order_date = ?, total_amount = ?, payment_status = ?, shipping_address = ? WHERE order_id = ?";
        JDBCUtils.execute(sql, order.getUserId(), order.getOrderDate(), order.getTotalAmount(), order.getPaymentStatus(), order.getShippingAddress(), order.getOrderId());
    }

    // 删除订单
    public static void deleteOrder(int orderId) throws SQLException {
        String sql = "DELETE FROM " + TABLE_NAME + " WHERE order_id = ?";
        JDBCUtils.execute(sql, orderId);
    }

    // 根据ID获取订单
    public static Order getOrderById(int orderId) throws SQLException {
        String sql = "SELECT * FROM " + TABLE_NAME + " WHERE order_id = ?";
        ResultSet resultSet = (ResultSet) JDBCUtils.execute(sql, orderId);
        if (resultSet.next()) {
            return createOrderFromResultSet(resultSet);
        }
        return null;
    }

    // 获取所有订单
    public static List<Order> getAllOrders() throws SQLException {
        List<Order> orders = new ArrayList<>();
        String sql = "SELECT * FROM " + TABLE_NAME;
        ResultSet resultSet = (ResultSet) JDBCUtils.execute(sql);
        while (resultSet.next()) {
            Order order = createOrderFromResultSet(resultSet);
            orders.add(order);
        }
        return orders;
    }

    // 创建Order对象从ResultSet
    private static Order createOrderFromResultSet(ResultSet resultSet) throws SQLException {
        int orderId = resultSet.getInt("order_id");
        int userId = resultSet.getInt("user_id");
        LocalDateTime orderDate = resultSet.getTimestamp("order_date").toLocalDateTime();
        BigDecimal totalAmount = resultSet.getBigDecimal("total_amount");
        String paymentStatus = resultSet.getString("payment_status");
        String shippingAddress = resultSet.getString("shipping_address");

        Order order = new Order();
        order.setOrderId(orderId);
        order.setUserId(userId);
        order.setOrderDate(orderDate);
        order.setTotalAmount(totalAmount);
        order.setPaymentStatus(paymentStatus);
        order.setShippingAddress(shippingAddress);

        return order;
    }
}
